<script setup lang="ts">
	import { ref, onMounted, reactive } from "vue";
	import { formRules } from "./utils/rule";
	import { FormProps } from "./utils/types";
	import ReCol from "@/components/ReCol";
  import { baseUrlApi, baseOaApi } from "@/api/utils";
  import type { UploadProps } from "element-plus";
  import { message } from "@/utils/message";
  import { Rank } from "@element-plus/icons-vue";
  import draggable from 'vuedraggable';
  import {
    workPlanHistoryApi
  } from "@/api/workPlanApi";
	const props = withDefaults(defineProps<FormProps>(), {
		formInline: () => ({
			title: "",
			status: 0,
			Id: 0,
		})
	});
	const ruleFormRef = ref();
	const newFormInline = ref(props.formInline);
  const dialogPagination = reactive({
    total: 0,
    pageSize: 10,
    currentPage: 1,
  });
	function getRef() {
		return ruleFormRef.value;
	}
	defineExpose({ getRef });

  onMounted(()=> {
    if(newFormInline.value.attachment && newFormInline.value.attachment.length > 0) {
      for (let item of newFormInline.value.attachment) {
        fileList.value.push({
          name: item,
          url: item
        })
      }

    }
  })
  const actionUrl = baseUrlApi + "/uploadFile/upload";

  const fileList = ref([])
  const handleAttachmentSuccess: UploadProps["onSuccess"] = (
    response,
    uploadFile
  ) => {
    // imgUrl.value = URL.createObjectURL(uploadFile.raw!);
    newFormInline.value.attachment = []
    for (let item of fileList.value) {
      if(item?.url) {
        newFormInline.value.attachment.push(item?.url)
      } else {
        newFormInline.value.attachment.push(baseOaApi + item?.response?.result?.path)
      }

    }
  };
  const beforeUpload = (file) => {

  }
  const addContent = () => {
    newFormInline.value.details.push({
      content: ''
    })
  }
  const delectContent = (index) => {
    newFormInline.value.details.splice(index, 1)
  }

  const statusChange = (val, row) => {
    if(val === 1) {
      row.completeRate = 100
    } else {
      row.completeRate = 0
    }

  }
  const blurCompleteRate = (val, row) => {
    if(row.completeRate === 100) {
      row.status = 1
    }
  }
  const openDetail = (url) => {
    window.open(url, '_blank');
  }
  const showPlanHistory = ref(false)
  const planHistoryChange = async() => {
    const res = await workPlanHistoryApi({
      page: dialogPagination.currentPage,
      perPage: dialogPagination.pageSize,
    })
    if(res?.code === 200) {
      newFormInline.value.planHistory = res?.result
      showPlanHistory.value = true
    }
  }
  const selectionVal = ref()
  const detailsSelectionChange = (val) => {
    selectionVal.value = val
  }
  const confirmDialog = () => {
    let arr = []
    if(selectionVal.value) {
      arr = [...newFormInline.value.details, ...selectionVal.value]
      const map = new Map()
      const newArr = arr.filter(key => !map.has(key.content) && map.set(key.content, 1))
      newFormInline.value.details = newArr

    }
    showPlanHistory.value = false
  }
  const handleSizeChange = (val: number) => {
    dialogPagination.page = 1;
    dialogPagination.perPage = val;
    planHistoryChange();
  }

  const handleCurrentChange = (val: number) => {
    dialogPagination.page = val;
    planHistoryChange()
  }
</script>

<template>
	<el-form ref="ruleFormRef" :model="newFormInline" :rules="formRules" label-width="auto">

    <el-row :gutter="30" v-if="newFormInline.title === '创建工作计划' || newFormInline.title === '编辑工作计划'">
      <re-col :value="24" :xs="24" :sm="24">
      	<el-form-item label="计划日期" prop="planDate">
          <el-date-picker
            v-model="newFormInline.planDate"
            type="date"
            placeholder="请选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
      	</el-form-item>
      </re-col>
      <re-col :value="24" :xs="24" :sm="24">
      	<el-form-item label="计划内容" required>
          <draggable
            v-model="newFormInline.details"
            ghost-class="ghost"
            animation="200"
            style="width: 100%"
          >
            <template #item="{ element, index }">
              <div class="form-item flex !w-full mb-[12px]">
                <!-- <span class="drag-handle">≡</span> -->
                <el-input v-model="element.content" clearable type="textarea" :rows="2" placeholder="请输入内容" />
                <el-button class="ml-[10px]" @click="addContent" v-if="index ===0" style="min-width: 40px;">+</el-button>
                <el-button class="ml-[10px]" @click="delectContent(index)" v-else type="danger" style="min-width: 40px;">-</el-button>
                <el-button class="ml-[10px] drag-handle" type="primary" style="min-width: 40px;"><el-icon><Rank /></el-icon></el-button>
              </div>
            </template>
          </draggable>
          <el-button link type="primary" @click="planHistoryChange">工作计划历史</el-button>
      	</el-form-item>
        <!-- <el-table :data="newFormInline.planHistory?.list" v-if="showPlanHistory" style="width: 100%;margin-bottom: 20px;" :header-cell-style="{background: 'var(--el-fill-color-light)', color: 'var(--el-text-color-primary)'}">
          <el-table-column type="expand">
            <template #default="props">
              <el-table :data="props.row.details" border @selection-change="detailsSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="内容" prop="content" />
                <el-table-column prop="status" label="状态" >
                  <template #default=" { row } ">
                    <span v-if="row.status === 0">未完成</span>
                    <span v-else-if="row.status === 1">已完成</span>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column prop="createUser.name" label="创建人" />
          <el-table-column prop="planDate" label="计划时间" />
          <el-table-column prop="statusStr" label="审核状态"/>
          <el-table-column prop="status" label="状态" >
            <template #default=" { row } ">
              <span v-if="row.status === 0">未完成</span>
              <span v-else-if="row.status === 1">已完成</span>
            </template>
          </el-table-column>
        </el-table> -->
      </re-col>
      <re-col :value="24" :xs="24" :sm="24">
      	<el-form-item label="附件">
      		<el-upload
      		  ref="uploadRef"
      		  :action="actionUrl"
      		  :on-success="handleAttachmentSuccess"
      		  v-model:file-list="fileList"
      		  :before-upload="beforeUpload"
            style="width: 100%;"
            drag
      		  multiple>
      		  <el-button link size="small" type="primary">上传附件</el-button>
      		</el-upload>
      	</el-form-item>
      </re-col>

    </el-row>
    <template v-if="newFormInline.title === '工作计划详情'">
      <el-row :gutter="30">

        <el-col :span="24">
          <el-form-item label="计划时间:">
            {{newFormInline.infoData.planDate}}
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="状态:">
            <span v-if="newFormInline.infoData.status === 0">未完成</span>
            <span v-else-if="newFormInline.infoData.status === 1">进行中</span>
            <span v-else>已完成</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="附件:">
            <template v-if="newFormInline.infoData?.attachments.length === 0">
                --
            </template>
            <template v-else>
              <div class="flex">
                <div v-for="item in newFormInline.infoData.attachments" :key="item" class="ml-[2px]">
                  <template v-if="item.substring(item.lastIndexOf('.') + 1) === 'jpg'">
                    <img src="../../assets/file-jpg.png" alt="" style="width: 24px;height: 24px;" @click="openDetail(item)"/>
                  </template>
                  <template v-if="item.substring(item.lastIndexOf('.') + 1) === 'jepg'">
                    <img src="../../assets/file-jepg.png" alt="" style="width: 24px;height: 24px;" @click="openDetail(item)"/>
                  </template>
                  <template v-if="item.substring(item.lastIndexOf('.') + 1) === 'png'">
                    <img src="../../assets/file-png.png" alt="" style="width: 24px;height: 24px;" @click="openDetail(item)"/>
                  </template>
                  <template v-if="item.substring(item.lastIndexOf('.') + 1) === 'doc' || item.substring(item.lastIndexOf('.') + 1) === 'docx'">
                    <img src="../../assets/file-doc.png" alt="" style="width: 24px;height: 24px;" @click="openDetail(item)"/>
                  </template>
                  <template v-if="item.substring(item.lastIndexOf('.') + 1) === 'pdf'">
                    <img src="../../assets/file-pdf.png" alt="" style="width: 24px;height: 24px;" @click="openDetail(item)"/>
                  </template>
                  <template v-if="item.substring(item.lastIndexOf('.') + 1) === 'exl' || item.substring(item.lastIndexOf('.') + 1) === 'xls' || item.substring(item.lastIndexOf('.') + 1) === 'xlsx'">
                    <img src="../../assets/file-exl.png" alt="" style="width: 24px;height: 24px;" @click="openDetail(item)"/>
                  </template>
                </div>
              </div>

            </template>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="创建人:">
            {{newFormInline.infoData.createUser.name}}
          </el-form-item>
        </el-col>
      </el-row>


      <el-table :data="newFormInline.details" style="width: 100%;margin-bottom: 20px;" :header-cell-style="{background: 'var(--el-fill-color-light)',
						color: 'var(--el-text-color-primary)'}">
        <el-table-column prop="content" label="序号" width="60">
          <template #default=" { row, $index } ">
            {{$index+1}}
          </template>
        </el-table-column>
        <el-table-column prop="content" label="内容" />
        <el-table-column prop="completeRate" label="完成比率(%)" width="120"/>
        <el-table-column prop="status" label="状态"  width="120">
          <template #default=" { row } ">
            <span v-if="row.status === 0">未完成</span>
            <span v-else-if="row.status === 1">已完成</span>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template v-if="newFormInline.title === '审核工作计划'">
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="newFormInline.status">
          <el-radio :label="1">已审核</el-radio>
          <el-radio :label="3">审核失败</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="newFormInline.remarks" type="textarea" :rows="3" placeholder="请输入"/>
      </el-form-item>
    </template>
    <template v-if="newFormInline.title === '完成工作计划'">
      <el-row :gutter="30">
        <re-col :value="12" :xs="24" :sm="24">
          <el-form-item label="计划日期" prop="planDate">
            <el-date-picker
              v-model="newFormInline.planDate"
              type="date"
              placeholder="请选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              disabled
              class="!w-[240px]"
            />
          </el-form-item>
        </re-col>
        <re-col :value="12" :xs="24" :sm="24">
          <el-form-item label="完成比例(%)" prop="completeRate">
            <el-input-number
              v-model="newFormInline.completeRate"
              :min="0"
              :max="100"
              controls-position="right"
              :precision="0"
              class="!w-[240px]"
            />
          </el-form-item>
        </re-col>
        <re-col :value="24" :xs="24" :sm="24">
          <el-table :data="newFormInline.details" style="width: 100%;margin-bottom: 20px;" :header-cell-style="{background: 'var(--el-fill-color-light)',
						color: 'var(--el-text-color-primary)'}">
            <el-table-column prop="content" label="序号" width="60">
              <template #default=" { row, $index } ">
                {{$index+1}}
              </template>
            </el-table-column>
            <el-table-column prop="content" label="内容">
              <template #default=" { row } ">
                {{row.content}}
              </template>
            </el-table-column>
            <el-table-column prop="content" label="状态" width="150">
              <template #default=" { row } ">
                <el-select v-model="row.status" placeholder="请选择" class="" @change="val =>statusChange(val,row)">
                  <el-option label="未完成" :value="0" />
                  <el-option label="已完成" :value="1" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="content" label="比例(%)" width="150">
              <template #default=" { row } ">
                <el-input-number
                  v-model="row.completeRate"
                  :min="0"
                  :max="100"
                  controls-position="right"
                  :precision="0"
                  :step="10"
                  class="!w-full"
                  @blur="val =>blurCompleteRate(val,row)"
                />
              </template>
            </el-table-column>
          </el-table>
        </re-col>
      </el-row>



    </template>
    <el-dialog
      v-model="showPlanHistory"
      title="历史工作计划"
      width="700"
      :close-on-click-modal="false"
    >
      <el-table :data="newFormInline.planHistory?.list" style="width: 100%;margin-bottom: 20px;" :header-cell-style="{background: 'var(--el-fill-color-light)', color: 'var(--el-text-color-primary)'}">
        <el-table-column type="expand">
          <template #default="props">
            <el-table :data="props.row.details" border @selection-change="detailsSelectionChange">
              <el-table-column type="selection" width="55" />
              <el-table-column label="内容" prop="content" />
              <el-table-column prop="status" label="状态" width="120">
                <template #default=" { row } ">
                  <span v-if="row.status === 0">未完成</span>
                  <span v-else-if="row.status === 1">已完成</span>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="createUser.name" label="创建人" />
        <el-table-column prop="planDate" label="计划时间" />
        <el-table-column prop="statusStr" label="审核状态"/>
        <el-table-column prop="status" label="状态" >
          <template #default=" { row } ">
            <span v-if="row.status === 0">未完成</span>
            <span v-else-if="row.status === 1">已完成</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex-bc p-[10px] w-full" style="justify-content: left;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="dialogPagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="dialogPagination.pageSize"
          background
          layout="total, sizes, prev, pager, next"
          :total="dialogPagination.total"
        >
        </el-pagination>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showPlanHistory = false">取消</el-button>
          <el-button type="primary" @click="confirmDialog">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
	</el-form>
</template>
<style scoped>

</style>
